package edu.nf.db.util.result;

import edu.nf.db.util.ResultSetHandler;
import edu.nf.db.util.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author zhu
 * @date 2024-05-08
 */
public class ColumnHandler<T> implements ResultSetHandler<T> {

    /**
     * 要获取列的下标
     */
    private Integer columnIndex;
    /**
     * 要获取列的列名
     */
    private String columnName;

    public ColumnHandler(Integer columnIndex) {
        this.columnIndex = columnIndex;
    }

    public ColumnHandler(String columnName) {
        this.columnName = columnName;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T handle(ResultSet rs) throws SQLException {

        if (rs.next()) {
            if (columnIndex == null) {
                return (T) RowProcessor.toValue(rs, columnName);
            }
            return (T) RowProcessor.toValue(rs, columnIndex);
        }
        return null;
    }
}
